package com.yuanxin.chooseimage;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.yuanxin.chooseimage.customutil.CustomConstant;
import com.yuanxin.chooseimage.customutil.LocalUtil;
import com.yuanxin.chooseimage.imagechoosemodule.MultiImageSelectorActivity;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by Administrator on 2016/3/10.
 */
public class LocalImageChooseModule extends ReactContextBaseJavaModule implements ImageResultCallback{


    private ArrayList<String> mSelectPath;
    private static final int REQUEST_IMAGE = 2;
    private static final int PERMISSION_CODE = 555;
    private static final int CAMERA_VIDEO = 200;
    private static final int CAMERA_PIC = 100;

    private Promise promise;

    public LocalImageChooseModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "ImagePickerManager";
    }

    /*
        选择照片，视频
     */
    @ReactMethod
    public void launchImageLibrary(final ReadableMap map,final Promise promise){

        Log.e("TAG","map---"+map);
        this.promise = promise;
        int total = 0;
        boolean isCut = false;
        String tag = "tag";
        String type = "json";
        boolean isShowCamera = false;
        int isPicVideo = 0;
        if(map != null) {
            total = map.getInt("maxCount");
            isShowCamera = map.getBoolean("isShowCamera");
            isPicVideo = map.getInt("IsChoose");
            Log.e("TAG", "total--" + total + "--isShowCamera--" + isShowCamera + "--isPicVideo--" + isPicVideo);

            SharedPreferences sp = getCurrentActivity().getSharedPreferences(CustomConstant.sharedName, Activity.MODE_PRIVATE);
            SharedPreferences.Editor edt = sp.edit();
            edt.putInt("total",total);
            edt.putBoolean("isCut",isCut);
            edt.putString("tag",tag);
            edt.putString("type",type);
            edt.putBoolean("isShowCamera",isShowCamera);
            edt.putInt("isPicVideo",isPicVideo);
            edt.putString("ShowChoosePath","launchImageLibrary");
            edt.apply();

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                Log.e("TAG","111111111111111111111");
                Intent intent = new Intent(getCurrentActivity(), PermissionActivity.class);
                getCurrentActivity().startActivityForResult(intent,PERMISSION_CODE);
            } else {
                Log.e("TAG","2222222222222222222");
                ChooseImage(total,isCut,tag,null,isShowCamera,isPicVideo);
            }
        } else {
            Log.e("TAG","Map是空的......");
        }

    }

    /*
        拍照录制
     */
    @ReactMethod
    public void launchCamera(final ReadableMap map,final Promise promise){

        Log.e("TAG","map---"+map);
        this.promise = promise;

        int IsCamera = map.getInt("IsCamera");
        int maxSecond = map.getInt("maxSecond");

        Log.e("TAG","IsCamera---"+IsCamera);

        if(IsCamera == 0){//照片
            // 激活系统的照相机进行拍照
            Intent intent = new Intent();
            intent.setAction("android.media.action.IMAGE_CAPTURE");
            intent.addCategory("android.intent.category.DEFAULT");

            //保存照片到指定的路径
            File file = new File(getSDCacheDir("yuanxinpic")+"/"+System.currentTimeMillis()+".png");
            Uri uri = Uri.fromFile(file);
            Log.e("TAG","camera---file---"+file+"---uri---"+uri);

            SharedPreferences sp = getCurrentActivity().getSharedPreferences(CustomConstant.sharedName, Activity.MODE_PRIVATE);
            SharedPreferences.Editor edt = sp.edit();
            edt.putString("PicFilePath", String.valueOf(file));
            edt.apply();

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            getCurrentActivity().startActivityForResult(intent, CAMERA_PIC);
        } else if(IsCamera == 1){//视频
            // 激活系统的照相机进行录像
            Intent intent = new Intent();
            intent.setAction("android.media.action.VIDEO_CAPTURE");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxSecond);

            // 保存录像到指定的路径
            File file = new File(getSDCacheDir("yuanxinvideo")+"/"+System.currentTimeMillis()+".mp4");
            Uri uri = Uri.fromFile(file);
            Log.e("TAG","video---file---"+file+"---uri---"+uri);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            getCurrentActivity().startActivityForResult(intent, CAMERA_VIDEO);
        }
    }

    public static String getSDCacheDir(String dirName){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            String path = Environment.getExternalStorageDirectory()+File.separator+dirName;
            File dir = new File(path);
            if(!dir.exists()){
                dir.mkdir();
            }
            return dir.getAbsolutePath();
        }else{
            return "";
        }
    }

    @ReactMethod
    public void showImagePicker(final ReadableMap map, final Promise promise)
    {
        Log.e("TAG","map---"+map);
        this.promise = promise;
        int total = 0;
        boolean isCut = false;
        String tag = null;
        String type = null;
        if(map != null) {
            total = map.getInt("maxCount");
            isCut = map.getBoolean("isEdite");
            tag = map.getString("tagString");
            type = map.getString("resultType");
            Log.e("TAG", "total--" + total + "--isCut--" + isCut + "--tag--" + tag);

            SharedPreferences sp = getCurrentActivity().getSharedPreferences(CustomConstant.sharedName, Activity.MODE_PRIVATE);
            SharedPreferences.Editor edt = sp.edit();
            edt.putInt("total",total);
            edt.putBoolean("isCut",isCut);
            edt.putString("tag",tag);
            edt.putString("type",type);
            edt.putBoolean("isShowCamera",true);
            edt.putInt("isPicVideo",0);
            edt.putString("ShowChoosePath","showImagePicker");
            edt.apply();

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                Log.e("TAG","111111111111111111111");
                Intent intent = new Intent(getCurrentActivity(), PermissionActivity.class);
                getCurrentActivity().startActivityForResult(intent,PERMISSION_CODE);
            } else {
                Log.e("TAG","2222222222222222222");
                ChooseImage(total,isCut,tag,null,true,0);
            }
        } else {
            Log.e("TAG","Map是空的......");
        }
    }

    public void ChooseImage(int total,boolean isCut,String tag,Activity activity,boolean IsShowCamera,int IsPicVideo){
        Log.e("TAG","total22222222--"+total+"--isCut--"+isCut+"--tag--"+tag);
        Log.e("TAG","3333333333333333333");
        LocalUtil.putStorageData(getReactApplicationContext() == null?activity:getReactApplicationContext(), CustomConstant.tag,tag);
        Log.e("TAG","4444444444444444444");
        int selectedMode=MultiImageSelectorActivity.MODE_MULTI;
        if (isCut)
        {
            selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
            Log.e("TAG","true");
        }else {
            selectedMode=MultiImageSelectorActivity.MODE_MULTI;
            Log.e("TAG","false");
        }
//        mSelectPath=((MainActivity)getCurrentActivity()).mSelectPath;
        Intent intent = new Intent(getReactApplicationContext(), MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, IsShowCamera);
        // 显示图片，视频
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_PIC_VIDEO, IsPicVideo);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, total);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);

        // 默认选择
        if(mSelectPath != null && mSelectPath.size()>0){
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
//        getCurrentActivity().startActivityForResult(intent, REQUEST_IMAGE);
        if (activity == null) {
            getReactApplicationContext().startActivityForResult(intent, REQUEST_IMAGE, null);
        }else{
            activity.startActivityForResult(intent,REQUEST_IMAGE);
        }
    }

    @ReactMethod
    public void choose(int total, boolean isCut, String tag)
    {
        Log.e("TAG","total--"+total+"--isCut--"+isCut+"--tag--"+tag);
        LocalUtil.putStorageData(getCurrentActivity(), CustomConstant.tag,tag);
        int selectedMode= MultiImageSelectorActivity.MODE_MULTI;
        if (isCut)
        {
            selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
        } else {
            selectedMode=MultiImageSelectorActivity.MODE_MULTI;
        }
//        mSelectPath=((MainActivity)getCurrentActivity()).mSelectPath;
        Intent intent = new Intent(getCurrentActivity(), MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, total);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);

        // 默认选择
        if(mSelectPath != null && mSelectPath.size()>0){
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
            promise.resolve(mSelectPath);
        }
        getCurrentActivity().startActivityForResult(intent, REQUEST_IMAGE);
    }

    public void sendEvent(ReactContext reactContext,
                          String eventName,
                          @Nullable WritableMap params) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    @Override
    public void meature(WritableMap writableMap) {
        Log.e("TAG","meature--"+writableMap);
        if(promise != null){
            Log.e("TAG","promise--"+promise);
            promise.resolve(writableMap);
            promise = null;
        }
//        sendEvent(this.getReactApplicationContext(), "ImageCapture", writableMap);
    }

    @Override
    public void LaunchMeature(WritableArray writableArray) {
        Log.e("TAG","meature--"+writableArray);
        if(promise != null){
            Log.e("TAG","promise--"+promise);
            promise.resolve(writableArray);
            promise = null;
        }
    }

    @Override
    public void CameraPic(WritableMap writableMap) {
        Log.e("TAG","CameraPic--"+writableMap);
        if(promise != null){
            Log.e("TAG","promise--"+promise);
            promise.resolve(writableMap);
            promise = null;
        }
    }

    @Override
    public void CameraVideo(WritableMap writableMap) {
        Log.e("TAG","CameraVideo--"+writableMap);
        if(promise != null){
            Log.e("TAG","promise--"+promise);
            promise.resolve(writableMap);
            promise = null;
        }
    }

}
